package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialPageDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.common.UserThreadLocal;
import com.heima.wemedia.service.WmMaterialService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.UUID;

@Service
@RequiredArgsConstructor
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<BaseMapper<WmMaterial>, WmMaterial> implements WmMaterialService {
    private final FileStorageService fileStorageService;

    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile file) {
        //1.校验文件类型
        //获取文件名
        String name = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(name); // 获取后缀名
        if ((!"jpg".equalsIgnoreCase(extension) && !"jpeg".equalsIgnoreCase(extension) && !"png".equalsIgnoreCase(extension))||extension==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (file == null || file.getSize() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.获取文件信息
        String uuid = UUID.randomUUID().toString();
        String filename = uuid + name.substring(name.lastIndexOf("."));

        //3.文件上传
        String url = null;
        try {
            InputStream inputStream = file.getInputStream();
            url = fileStorageService.uploadImgFile("", filename, inputStream);
        } catch (IOException e) {
            log.error("文件上传失败!",e);
            return ResponseResult.errorResult(201, "文件上传失败！");
        }
        //4.保存图片信息到数据库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUrl(url);
        wmMaterial.setType((short) 0);
        wmMaterial.setIsCollection((short) 0);
        String userId = UserThreadLocal.getUserId();
        wmMaterial.setUserId(Long.parseLong(userId));
        wmMaterial.setCreatedTime(LocalDateTime.now());
        save(wmMaterial);
        return ResponseResult.okResult(200, "上传成功");
    }

    /**
     * 分页查询
     *
     * @param wmMaterialPageDto
     * @return
     */
    @Override
    public ResponseResult pagePicture(WmMaterialPageDto wmMaterialPageDto) {
        if (ObjectUtils.isEmpty(wmMaterialPageDto)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.查询图片
        String userId = UserThreadLocal.getUserId();
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(wmMaterialPageDto.getIsCollection() != null,
                WmMaterial::getIsCollection,
                wmMaterialPageDto.getIsCollection())
                .eq(WmMaterial::getUserId, Long.parseLong(userId))
                .orderByDesc(WmMaterial::getCreatedTime);

        Page<WmMaterial> wmMaterialPage = page(new Page<>(wmMaterialPageDto.getPage(), wmMaterialPageDto.getSize()), queryWrapper);

        //封装返回结果
        PageResponseResult pageResponseResult = new PageResponseResult();
        Long total = wmMaterialPage.getTotal();
        Integer totalInt = Integer.parseInt(total.toString());
        pageResponseResult.setTotal(totalInt);
        pageResponseResult.setData(wmMaterialPage.getRecords());
        pageResponseResult.setCurrentPage(wmMaterialPageDto.getPage());
        pageResponseResult.setSize(wmMaterialPageDto.getSize());
        return pageResponseResult;
    }
}
